<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>采购单添加</title>
    <link href="../layui/css/layui.css" rel="stylesheet">
</head>
<body class="layui-layout-body">
    <div class="layui-layout layui-layout-admin">
        <!-- 头部区域 -->
        <div class="layui-header">
            <div class="layui-logo layui-hide-xs layui-bg-black">小药店管理系统</div>
            <ul class="layui-nav layui-layout-right">
                <li class="layui-nav-item layui-hide layui-show-sm-inline-block">
                    <a href="javascript:;">
                        <img src="//unpkg.com/outeres@0.0.10/img/layui/icon-v2.png" class="layui-nav-img">
                        欢迎, <span id="username">管理员</span>
                    </a>
                    <dl class="layui-nav-child">
                        <dd><a href="javascript:;" onclick="logout()">退出</a></dd>
                    </dl>
                </li>
            </ul>
        </div>

        <!-- 左侧导航区域 -->
        <div class="layui-side layui-bg-black">
            <div class="layui-side-scroll">
                <ul class="layui-nav layui-nav-tree" lay-filter="test">
                    <li class="layui-nav-item layui-nav-itemed">
                        <a href="javascript:;">采购管理</a>
                        <dl class="layui-nav-child">
                            <dd><a href="../supplier/supplier.html">供应商信息管理</a></dd>
                            <dd><a href="../supplier/drug.html">药品信息管理</a></dd>
                            <dd><a href="add.html">采购单添加</a></dd>
                            <dd><a href="list.html">采购单管理</a></dd>
                        </dl>
                    </li>
                    <li class="layui-nav-item">
                        <a href="javascript:;">销售管理</a>
                        <dl class="layui-nav-child">
                            <dd><a href="../sales/add_xiaoshoudan.html">销售单添加管理</a></dd>
                            <dd><a href="../sales/xiaoshoumingxi.html">销售明细管理</a></dd>
                        </dl>
                    </li>
                    <li class="layui-nav-item">
                        <a href="javascript:;">药店统计管理</a>
                        <dl class="layui-nav-child">
                            <dd><a href="../statistics/instock.html">入库统计</a></dd>
                            <dd><a href="../statistics/sales.html">销售统计</a></dd>
                            <dd><a href="../statistics/stock.html">库存查询</a></dd>
                        </dl>
                    </li>
                    <li class="layui-nav-item">
                        <a href="javascript:;">人事管理</a>
                        <dl class="layui-nav-child">
                            <dd><a href="javascript:;">员工添加</a></dd>
                            <dd><a href="javascript:;">员工管理</a></dd>
                        </dl>
                    </li>
                    <li class="layui-nav-item">
                        <a href="javascript:;">打印管理</a>
                        <dl class="layui-nav-child">
                            <dd><a href="../print/ruku.html">入库单</a></dd>
                            <dd><a href="../print/chuku.html">出库单</a></dd>
                        </dl>
                    </li>
                    <li class="layui-nav-item">
                        <a href="javascript:;">系统管理</a>
                        <dl class="layui-nav-child">
                            <dd><a href="../user/xiuGaiMiMa.html">修改密码</a></dd>
                        </dl>
                    </li>
                </ul>
            </div>
        </div>

        <!-- 内容主体区域 -->
        <div class="layui-body">
            <div style="padding: 15px;">
                <!-- 面包屑导航 -->
                <div class="layui-card">
                    <div class="layui-card-body">
                        <span class="layui-breadcrumb">
                            <a href="../index.html">首页</a>
                            <a href="list.html">采购管理</a>
                            <a><cite>添加采购单</cite></a>
                        </span>
                    </div>
                </div>
                
                <!-- 采购单表单 -->
                <div class="layui-form" lay-filter="addForm" style="padding: 20px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label">采购单号</label>
                        <div class="layui-input-block">
                            <input type="text" name="danjuhao" class="layui-input" readonly>
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">经手人</label>
                        <div class="layui-input-block">
                            <select name="jingshouren" lay-verify="required" lay-search>
                                <option value="">请选择经手人</option>
                            </select>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">采购日期</label>
                        <div class="layui-input-block">
                            <input type="text" name="shijian" class="layui-input" id="date" readonly>
                        </div>
                    </div>

                    <!-- 药品选择区域 -->
                    <div class="layui-form-item">
                        <label class="layui-form-label">选择药品</label>
                        <div class="layui-input-inline" style="width: 300px;">
                            <select name="drugId" lay-search lay-filter="drugSelect">
                                <option value="">请选择药品</option>
                            </select>
                        </div>
                        <div class="layui-input-inline" style="width: 150px;">
                            <input type="number" name="quantity" placeholder="请输入数量" class="layui-input" min="1">
                        </div>
                        <div class="layui-input-inline" style="width: 150px;">
                            <input type="text" name="price" placeholder="单价" class="layui-input" readonly>
                        </div>
                        <button type="button" class="layui-btn" lay-submit lay-filter="addDetail">添加到明细</button>
                    </div>

                    <!-- 明细表格 -->
                    <table id="detailTable" lay-filter="detailTable"></table>
                    
                    <!-- 总金额显示 -->
                    <div class="layui-form-item">
                        <label class="layui-form-label">总金额</label>
                        <div class="layui-input-block">
                            <input type="text" name="zongjiage" class="layui-input" readonly>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">备注</label>
                        <div class="layui-input-block">
                            <textarea name="beizhu" class="layui-textarea" placeholder="请输入备注（选填）"></textarea>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button type="button" class="layui-btn" lay-submit lay-filter="saveProcurement">保存采购单</button>
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                        </div>
                    </div>
                </div>

                <script src="../layui/layui.js"></script>
                <script>
                layui.use(['form', 'laydate', 'table'], function(){
                    var form = layui.form;
                    var laydate = layui.laydate;
                    var table = layui.table;
                    var $ = layui.$;
                    
                    // 初始化日期选择器
                    laydate.render({
                        elem: '#date',
                        value: new Date(),
                        field: 'shijian',
                        type: 'date',  // 只显示年月日
                        format: 'yyyy-MM-dd'  // 设置日期格式
                    });

                    // 生成采购单号
                    var date = new Date();
                    var danjuhao = 'CG' + date.getFullYear() + 
                                 String(date.getMonth() + 1).padStart(2, '0') + 
                                 String(date.getDate()).padStart(2, '0') + 
                                 String(Math.floor(Math.random() * 1000)).padStart(3, '0');
                    $('input[name="danjuhao"]').val(danjuhao);

                    // 加载负责人列表
                    $.ajax({
                        url: '/api/procurement/employees',
                        type: 'GET',
                        success: function(res) {
                            console.log('获取员工列表响应:', res);  // 添加调试日志
                            if(res.code === 0 && res.data) {
                                var html = '<option value="">请选择负责人</option>';
                                res.data.forEach(function(item) {
                                    html += '<option value="' + item.name + '">' + item.name + ' - ' + item.position + '</option>';
                                });
                                $('select[name="jingshouren"]').html(html);
                                form.render('select');
                            } else {
                                layer.msg('加载负责人列表失败: ' + (res.msg || '未知错误'));
                                console.error('加载负责人列表失败:', res);  // 添加错误日志
                            }
                        },
                        error: function(xhr, status, error) {
                            layer.msg('加载负责人列表失败: ' + error);
                            console.error('加载负责人列表请求失败:', {xhr: xhr, status: status, error: error});  // 添加错误日志
                        }
                    });

                    // 初始化明细表格
                    var detailTable = table.render({
                        elem: '#detailTable',
                        cols: [[
                            {field: 'drugName', title: '药品名称', width: 200},
                            {field: 'quantity', title: '数量', width: 100},
                            {field: 'price', title: '单价', width: 100},
                            {field: 'amount', title: '金额', width: 100},
                            {title: '操作', width: 100, templet: '#operationTpl', fixed: 'right'}
                        ]],
                        data: [],
                        limit: 1000
                    });

                    // 监听药品选择
                    form.on('select(drugSelect)', function(data){
                        if(data.value){
                            // 获取药品信息
                            $.get('/api/drug/' + data.value, function(res){
                                if(res.code === 0){
                                    $('input[name="price"]').val(res.data.price);
                                }
                            });
                        }
                    });

                    // 加载药品列表
                    $.get('/api/drug/list', function(res){
                        if(res.code === 0){
                            var html = '<option value="">请选择药品</option>';
                            res.data.forEach(function(item){
                                html += '<option value="' + item.id + '">' + item.drugName + '</option>';
                            });
                            $('select[name="drugId"]').html(html);
                            form.render('select');
                        }
                    });

                    // 添加明细
                    form.on('submit(addDetail)', function(data){
                        var detail = {
                            drugId: data.field.drugId,
                            drugName: $('select[name="drugId"] option:selected').text(),
                            quantity: parseInt(data.field.quantity),
                            price: parseFloat(data.field.price),
                            amount: parseFloat(data.field.price) * parseInt(data.field.quantity),
                            totalPrice: parseFloat(data.field.price) * parseInt(data.field.quantity)
                        };
                        
                        var tableData = table.getData('detailTable');
                        tableData.push(detail);
                        detailTable.reload({
                            data: tableData
                        });
                        
                        // 计算总金额
                        var total = tableData.reduce(function(sum, item){
                            return sum + item.amount;
                        }, 0);
                        $('input[name="zongjiage"]').val(total.toFixed(2));
                        
                        // 清空选择
                        $('select[name="drugId"]').val('');
                        $('input[name="quantity"]').val('');
                        $('input[name="price"]').val('');
                        form.render('select');
                        
                        return false;
                    });

                    // 保存采购单
                    form.on('submit(saveProcurement)', function(data){
                        var tableData = table.getData('detailTable');
                        if(tableData.length === 0){
                            layer.msg('请添加采购明细');
                            return false;
                        }
                        
                        // 验证必填字段
                        if(!data.field.jingshouren){
                            layer.msg('请选择经手人');
                            return false;
                        }
                        
                        var procurement = {
                            danjuhao: data.field.danjuhao,
                            jingshouren: data.field.jingshouren,  // 现在直接传递的是名字
                            shijian: data.field.shijian,
                            beizhu: data.field.beizhu || '',
                            details: tableData,
                            zongjiage: parseFloat($('input[name="zongjiage"]').val())
                        };
                        
                        $.ajax({
                            url: '/api/procurement/add',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(procurement),
                            success: function(res){
                                if(res.code === 0){
                                    layer.msg('保存成功', {
                                        icon: 1,
                                        time: 2000
                                    }, function(){
                                        location.href = 'list.html';
                                    });
                                } else {
                                    layer.msg(res.msg);
                                }
                            }
                        });
                        
                        return false;
                    });

                    // 监听表格工具条
                    table.on('tool(detailTable)', function(obj){
                        if(obj.event === 'del'){
                            // 获取当前表格数据
                            var tableData = table.getData('detailTable');
                            // 删除当前行
                            tableData.splice(obj.tr.data('index'), 1);
                            // 重新加载表格
                            detailTable.reload({
                                data: tableData
                            });
                            // 重新计算总金额
                            var total = tableData.reduce(function(sum, item){
                                return sum + item.amount;
                            }, 0);
                            $('input[name="zongjiage"]').val(total.toFixed(2));
                        }
                    });
                });
                </script>
                
                <!-- 明细表格操作模板 -->
                <script type="text/html" id="operationTpl">
                    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                </script>
            </div>
        </div>
    </div>

    <script>
    // 添加退出功能
    function logout() {
        layui.use(['jquery', 'layer'], function(){
            var $ = layui.$;
            var layer = layui.layer;
            
            $.ajax({
                url: '/user/logout',
                type: 'GET',
                success: function(res) {
                    if(res.code === 0) {
                        window.location.href = '/login/login.html';
                    } else {
                        layer.msg(res.msg || '退出失败', {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('服务器错误', {icon: 2});
                }
            });
        });
    }
    </script>
</body>
</html> 